//
//  SFEmoticonCell.m
//  SFEmoticon
//
//  Created by 许博 on 16/7/18.
//  Copyright © 2016年 许博. All rights reserved.
//

#import "SFEmoticonCell.h"
#import "SFEmoticon.h"
#import "UIImage+SFEmoticon.h"

#import "SFEmoticonButton.h"

@implementation SFEmoticonCell


#pragma mark - 设置数据
- (void)setEmoticons:(NSArray<SFEmoticon *> *)emoticons {
    _emoticons = emoticons;
    
    for (UIView *v in self.contentView.subviews) {
        v.hidden = YES;
    }
    self.contentView.subviews.lastObject.hidden = NO;
    
    NSInteger index = 0;
    for (SFEmoticon *e in _emoticons) {
        SFEmoticonButton *btn = self.contentView.subviews[index++];
        
        btn.emoticon = e;
    }
}

#pragma mark - 构造函数
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareUI];
        
    }
    return self;
}



#pragma mark - 监听方法


- (void)clickEmoticonButton:(SFEmoticonButton *)button {
    [self.delegate emoticonCellDidSelectedEmoticon:button.emoticon isRemoved:button.isDeleteButton];
}

#pragma mark - 设置界面
- (void)prepareUI {
    NSInteger rowCount = 3;
    NSInteger colCount = 7;
    
    CGFloat leftMargin = 8;
    CGFloat bottomMargin = 16;
    
    CGFloat w = ceil((self.bounds.size.width - 2 * leftMargin) / colCount);
    CGFloat h = ceil((self.bounds.size.height - bottomMargin) / rowCount);
    
    for (NSInteger i = 0; i < 21; i++) {
        NSInteger col = i % colCount;
        NSInteger row = i / colCount;
        
        CGRect rect = CGRectMake(col * w + leftMargin, row * h, w, h);
        UIButton *button = [SFEmoticonButton emoticonButtonWithFrame:rect tag:i];
        
        [self.contentView addSubview:button];
        
        [button addTarget:self
                   action:@selector(clickEmoticonButton:)
         forControlEvents:UIControlEventTouchUpInside];
    }
    
    // 删除按钮
    ((SFEmoticonButton *)self.contentView.subviews.lastObject).deleteButton = YES;
    
    
    
}

@end
